package cn.lz;

import cn.lz.pojo.tang;
import cn.lz.util.DateUtils;
import cn.lz.util.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.istack.internal.logging.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.util.Date;

import static cn.lz.util.JSONUtils.isJSONValid;

public class HelloWorldHandler extends IoHandlerAdapter{

    private static final Logger logger = Logger.getLogger(HelloWorldHandler.class);

//   url地址
    static String ServiceAddress = "http://mobopower.cn/mobopower";
    static String hostName = "http://localhost:8080/Jtcp/login"; //TODO 第一批D设备协议只支持IP


    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        // TODO Auto-generated method stub
        super.exceptionCaught(session, cause);
    }

    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        // TODO Auto-generated method stub
        String string=message.toString();
        System.out.println("接收到的消息：" + string);

        JSONObject jsonObject =null;
        //转对象
        if(isJSONValid(string)){
            //是标准的json串
            jsonObject =JSON.parseObject(string);
        }else {
            //不是标准的json串
            jsonObject =JSON.parseObject( string.substring(6));
        }

        //初始化
        String reply=" hi, i am server";
        tang t =new tang();
        // 注册
        if(jsonObject.get("CD")!=null&&jsonObject.get("CD").equals("Z")){
            String  responsestr = HttpRequest.sendPost(hostName, "{" + "ID:" + jsonObject.get("ID") + ";sessionid:" + session.getId() + ";}");
            logger.info("responsestr========:" + responsestr);

           if(responsestr.equals("3400001")){
               //发送成功协议给对方
               //  发送给设备的协议：000132{"RE":"Y","OD":"SAA00377_1","IP":"39.108.213.213",
//               "PT":"10643","TM":"1535119437",
//              "MS":"72042","PW":"123456","VR":"","UL":"","CR":""}
               t.setRE("Y");
                // todo tangxianliang 的需要替换
               t.setOD((String) jsonObject.get("OD"));
               t.setIP("tangxianlang");
               t.setPT("tangxianliang");
               t.setTM(DateUtils.UnixDate(new Date()));
                // todo 心跳间隔
               t.setMS("10000");
               // todo 目标服务器密码，设备未授权，服务器返回空
               t.setPW("123456");
               t.setVR("");
               t.setUL("");
               t.setCR("");

           }else {
               //失败

           }
           //对象转json
            String s = JSONObject.toJSONString(t);
           //拼接的数据
            reply=String.format("%06d", s.length())+s;

            logger.info("注册发送的数据是：" + reply);
        }

        // I-心跳
        if(jsonObject.get("CD")!=null&&jsonObject.get("CD").equals("I")){
        //  协议：000069{"RE":"Y","OD":"5896348_1","CD":"I","ID":"5896348","TM":"1526377009"}
            t.setRE("Y");
            t.setOD("5896348_1");
            t.setCD("I");
            t.setID("5896348");
            t.setTM(DateUtils.UnixDate(new Date()));

            //对象转json
            String s = JSONObject.toJSONString(t);
            //拼接的数据
            reply=String.format("%06d", s.length())+s;
            logger.info("心跳发送的数据是：" + reply);
        }

//        B-租赁 H-归还 J-检修 R-重启 O-关机
        //给客户端发送消息


        //发送给客服端
        session.write(reply);

        System.out.println("消息發送了");
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("message have been sent");
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("closed session");
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("session created");
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
        // TODO Auto-generated method stub
        System.out.println("IDLE "+session.getIdleCount(status));
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("session opened");
    }

}